<?php

namespace App\Http\Controllers\Api\Goods;

use DB;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\Models\Goods\GoodsSale;

use App\Models\Customer\CustCollection;

class CollectController extends Controller
{

    /**
     * 新增收藏
     * @param Request $request
     * @return array
     */
    public function add(Request $request)
    {

        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $id_str = $request->input('id');
        $data = explode(',',$id_str);

        $pcustID = get_customer_id($session_id, $platform);

        if ( empty($data) || !is_array($data) ) {
            return response()->json(['code' => 100000, 'message' => '参数错误']);
        }

        foreach($data as &$postID){
            $goods = GoodsSale::getCache($postID);
            if (!$goods) {
                return response()->json(['code' => 100001, 'message' => '商品信息不存在']);
            }

            $collect = CustCollection::where(['pcustID' => $pcustID, 'postID' => $postID])->first();
            if ($collect) {
                return response()->json(['code' => 100002, 'message' => '商品【'. $goods['goodsName'] .'】已收藏']);
            }

            $collection_obj = new CustCollection();
            $collection_obj->uuid = makeUuid();
            $collection_obj->timeStamp = Carbon::now();
            $collection_obj->creator = 'system';
            $collection_obj->createTime = Carbon::now();
            $collection_obj->pcustID = $pcustID;
            $collection_obj->postID = $postID;
            $collection_obj->save();
        }

        return response()->json(['code' => 200, 'message' => 'ok']);
    }

    /**
     * 删除收藏
     * @param Request $request
     * @return array
     */
    public function del(Request $request)
    {

        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $id_str = $request->input('id');
        $data = explode(',',$id_str);

        $pcustID = get_customer_id($session_id, $platform);

        if ( empty($data) || !is_array($data) ) {
            return response()->json(['code' => 100000, 'message' => '参数错误']);
        }

        foreach( $data as &$postID ){
            CustCollection::where(['pcustID' => $pcustID, 'postID' => $postID])->delete();
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $data]);
    }

}